package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Remind;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.*;
import com.fz.us.oa.core.entity.com.Meeting;
import com.fz.us.oa.core.entity.com.MeetingSign;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.MeetingService;
import com.fz.us.oa.core.service.com.MeetingSignService;
import com.fz.us.oa.core.service.com.ScheduleService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/21.
 */
@Controller
@RequestMapping(value = "/com/meeting")
public class MeetingController extends BaseController {
    private static final long serialVersionUID = 3685937162265566147L;

    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private MeetingService meetingService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private RemindService remindService;
    @Autowired
    private UserService userService;
    @Autowired
    private FileManagerService fileManagerService;
    @Autowired
    private MeetingSignService meetingSignService;


    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record,String meet) {
        if (StringUtils.isNotEmpty(keyId)){
            Meeting meeting=meetingService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("meeting", meeting);
        }
        model.addAttribute("meet", meet);
        model.addAttribute("user", user);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/meeting_input";
    }

    /**
     * 日历中弹出的只读页面
     */
    @RequestMapping(value = "readDialog", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String readDialog(@CurrentUser User user, Model model, String keyId) {

        Meeting meeting = meetingService.get(keyId);
        model.addAttribute("keyId", keyId);
        model.addAttribute("meeting",meeting);
        model.addAttribute("user",user);

        return "/com/meeting_read_dialog";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            Meeting meeting=meetingService.get(keyId);
            if(meeting.getFile() != null && meeting.getFile().size()>0){
                for(FileManage f:meeting.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            if(!meeting.getProcessState().name().equals("Destroy")&&!meeting.getProcessState().name().equals("Finished")&&!meeting.getProcessState().name().equals("Deny")){
                TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
                int stepNo = taskEntity.getStepNo();

                String isEdit =  isEdit(keyId);
                model.addAttribute("stepNo", stepNo);
                model.addAttribute("isEdit", isEdit);
            }
            model.addAttribute("meeting", meeting);
            model.addAttribute("fileId", fileId);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/meeting_read";
    }

    /**
     * 历史副本只读页面
     */
    @RequestMapping(value = "readHistory", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String readHistory(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            Meeting meeting=meetingService.get(keyId);
            if(meeting.getFile() != null && meeting.getFile().size()>0){
                for(FileManage f:meeting.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            if(!meeting.getProcessState().name().equals("Destroy")&&!meeting.getProcessState().name().equals("Finished")){
                TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
                int stepNo = taskEntity.getStepNo();

                String isEdit =  isEdit(keyId);
                model.addAttribute("stepNo", stepNo);
                model.addAttribute("isEdit", isEdit);
            }
            model.addAttribute("meeting", meeting);
            model.addAttribute("fileId", fileId);
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/meeting_read_history";
    }

    /**
     * 保存Model数据
     */
    private Meeting saveModel(User user, String keyId, String isOut,String isPublic,String name,
                              String datStart, String timStart, String datEnd, String timEnd, String subject,
                              String userId, String userIds,String outermen, String address,String aidSets, String otherSet) throws ParseException {

        Meeting meeting = null;
        if (StringUtils.isBlank(keyId)) {
            meeting = new Meeting();
            meeting.setCreater(user);
            meeting.setCompany(user.getCompany());
        } else {
            meeting = meetingService.get(keyId);
        }

        if (StringUtils.isNotBlank(isOut)) {
            meeting.setIsOut(Integer.valueOf(isOut));
        }

        if (StringUtils.isNotBlank(isPublic)) {
            meeting.setIsPublic(Integer.valueOf(isPublic));
        }

        if (StringUtils.isNotBlank(name)) {
            meeting.setName(name);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        if (StringUtils.isNotBlank(datStart)) {
            meeting.setDatStart(sdf.parse(datStart));
            if (StringUtils.isNotBlank(timStart)) {
                meeting.setTimStart(sdf2.parse(datStart + " " + timStart));
            }
        }

        if (StringUtils.isNotBlank(datEnd)) {
            meeting.setDatEnd(sdf.parse(datEnd));
            if (StringUtils.isNotBlank(timEnd)) {
                meeting.setTimEnd(sdf2.parse(datEnd + " " + timEnd));
            }
        }

        if (StringUtils.isNotBlank(subject)) {
            meeting.setSubject(subject);
        }

        if (StringUtils.isNotBlank(userId)) {
            meeting.setChief(userService.get(userId));
        }

        if (StringUtils.isNotBlank(userIds)) {
            String[] uids = StringUtils.split(userIds,",");
            HashSet<User> users = new HashSet<User>();
            for (String uid : uids) {
                User u = userService.get(uid);
                users.add(u);
            }
            meeting.setParticipants(users);
        }

        if (StringUtils.isNotBlank(outermen)) {
            meeting.setOutermen(outermen);
        }

        if (StringUtils.isNotBlank(address)) {
            meeting.setAddress(address);
        }

        if (StringUtils.isNotBlank(aidSets)) {
            meeting.setAidSets(aidSets);
            if(aidSets.indexOf("07")>-1){
                if (StringUtils.isNotBlank(otherSet)) {
                    meeting.setOtherSet(otherSet);
                }
            }
        }

        if (meeting.getForm() == null) {
            meeting.setForm("会议安排登记表");
        }

        return meeting;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId, String isOut,String isPublic,String name,
                       String datStart, String timStart, String datEnd, String timEnd, String subject,
                       String userId, String userIds,String outermen, String address,String aidSets, String otherSet) throws ParseException{

        Map<String,Object> rMap=new HashMap<String,Object>();
        Meeting meeting = saveModel(user, keyId, isOut, isPublic, name, datStart, timStart, datEnd, timEnd, subject, userId, userIds, outermen, address, aidSets, otherSet);
        if(StringUtils.isNotEmpty(keyId)){
            meetingService.update(meeting);
            rMap.put("message", "更新成功");
        } else {
            meetingService.save(meeting, "com.fz.us.oa.core.entity.com.Meeting");
            rMap.put("message","保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     *提交操作
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,String isOut,String isPublic,String name,
                         String datStart, String timStart, String datEnd, String timEnd, String subject, String userId, String userIds,
                         String outermen, String address,String aidSets, String otherSet, String curDutyId, String comment) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        Meeting meeting = saveModel(user, keyId, isOut, isPublic, name, datStart, timStart, datEnd, timEnd, subject, userId, userIds, outermen, address, aidSets, otherSet);

        if (StringUtils.isNotEmpty(keyId)) {
            meetingService.approve(meeting, dutyService.get(curDutyId), comment);
        } else {
            meetingService.commit(meeting, "com.fz.us.oa.core.entity.com.Meeting", dutyService.get(curDutyId));
        }

        if(meeting.getProcessState().name().equals("Finished")){
            doFinished(meeting);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        Meeting meeting=meetingService.get(keyId);
        meetingService.approve(meeting, dutyService.get(curDutyId), comment);

        if(meeting.getProcessState().name().equals("Finished")){
            doFinished(meeting);
        }

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(Meeting meeting){
        List<MeetingSign> meetingSignList=new ArrayList<MeetingSign>();
        for(User user1:meeting.getParticipants()){
            MeetingSign meetingSign=new MeetingSign();
            meetingSign.setUser(user1);
            meetingSign.setSignPlace(meeting.getAddress());
            meetingSignService.save(meetingSign);
            meetingSignList.add(meetingSign);
        }

        meeting.setNumStatus(1);
        meeting.setMeetingSigns(meetingSignList);
        meetingService.update(meeting);

        //发送提醒
        Remind remind = new Remind();
        remind.setUser(meeting.getChief());
        remind.setBussinessKey("meeting");
        remind.setKeyId(meeting.getId());
        remind.setContent("您有一次新的会议安排，请查看");
        remindService.save(remind);
        for(User user1:meeting.getParticipants()){
            Remind remind1 = new Remind();
            remind1.setUser(user1);
            remind1.setBussinessKey("meeting");
            remind1.setKeyId(meeting.getId());
            remind1.setContent("您有一次新的会议安排，请查看");
            remindService.save(remind1);
        }
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Meeting meeting=meetingService.get(keyId);
            meetingService.back(meeting, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message", "退回成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            Meeting meeting=meetingService.get(keyId);
            meetingService.deny(meeting, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表 日历上的
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user, @RequestParam(required = false) int source,
                                    @RequestParam() int catalog, @RequestParam() String start, @RequestParam() String end) throws ParseException {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.asc);
        SearchResultPaging searchResult = null;

        List<Rule> rules = new ArrayList<Rule>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        rules.add(RuleHelper.eq("company", company));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的
        rules.add(RuleHelper.eq("processState",FlowEnum.ProcessState.Finished));
        rules.add(RuleHelper.ge("timStart", sdf.parse(start)));
        rules.add(RuleHelper.le("timEnd", sdf.parse(end)));
        rules.add(RuleHelper.ne("processState", FlowEnum.ProcessState.Destroy)); // 排除历史文档
        rules.add(RuleHelper.ne("numStatus", -1));  // 排除已取消的会议
        if (source == 1) {
            rules.add(RuleHelper.eq("isOut", 1));
        }

            //所有单子
//            searchResult = meetingService.paging(null, rules, order,
//                    "com.fz.us.oa.core.entity.com.Meeting",
//                    new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished}, null);
        searchResult = meetingService.findPagingBySearch(null,rules,order);

        List<Meeting> meetingList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Meeting meeting: meetingList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(meeting.getId())?"":meeting.getId());
            rMap.put("name", StringUtils.isEmpty(meeting.getName())?"":meeting.getName());
            rMap.put("subject", StringUtils.isEmpty(meeting.getSubject())?"":meeting.getSubject());

            Date now = new Date();
            Date start1 = meeting.getTimStart();
            Date end1 = meeting.getTimEnd();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            rMap.put("start", sdf1.format(start1));
            rMap.put("end", sdf.format(end1));

            if(now.getTime() > end1.getTime()){  // 已召开
                rMap.put("className", "purple");
            } else if (now.getTime() > start1.getTime()) {   // 召开中
                rMap.put("className", "warning");
            } else {    // 未召开
                rMap.put("className", "mint");
            }
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 列表 视图上的
     */
    @RequestMapping(value = "listView", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> listView(@CurrentUser User user,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) throws ParseException {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;
        List<Rule> rules = getSearchFilterRules(pager.getSearch(), filters);
        rules.add(RuleHelper.ne("processState", FlowEnum.ProcessState.Destroy)); // 排除历史文档
        rules.add(RuleHelper.eq("company", company));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的



        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //所有会议
                rules.add(RuleHelper.or(
                        RuleHelper.eq("processState", FlowEnum.ProcessState.Finished),
                        RuleHelper.eq("isPublic", 1),
                        RuleHelper.eq("creater", user),
                        RuleHelper.eq("chief", user),
                        RuleHelper.sql("'" + user.getId() + "' in (select participants_id from ec_meeting_sys_user where ec_meeting_id = this_.id )")));

//                searchResult = meetingService.paging(null,rules,order,
//                        "com.fz.us.oa.core.entity.com.Meeting", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
                searchResult = meetingService.findPagingBySearch(null,rules,order);
            }else if(viewtype.equals("2")){
                //我的会议
                rules.add(RuleHelper.or(
                        RuleHelper.eq("processState", FlowEnum.ProcessState.Finished),
                        RuleHelper.eq("chief", user),
                        RuleHelper.sql("'" + user.getId() + "' in (select participants_id from ec_meeting_sys_user where ec_meeting_id = this_.id )")));

//                searchResult = meetingService.paging(null,rules,order,
//                        "com.fz.us.oa.core.entity.com.Meeting", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
                searchResult = meetingService.findPagingBySearch(null,rules,order);
            }
        }else{
            //所有单子
//            searchResult = meetingService.paging(null,rules,order,
//                    "com.fz.us.oa.core.entity.com.Meeting",
//                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
            searchResult = meetingService.findPagingBySearch(null,rules,order);
        }

        List<Meeting> meetingList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Meeting meeting: meetingList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(meeting.getId())?"":meeting.getId());
            rMap.put("name", StringUtils.isEmpty(meeting.getName())?"":meeting.getName());
            rMap.put("address", StringUtils.isEmpty(meeting.getAddress())?"":meeting.getAddress());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            rMap.put("datStart", (meeting.getDatStart()==null)?"":sdf.format(meeting.getDatStart()));
            rMap.put("chief", (meeting.getChief()==null)?"":meeting.getChief().getName());

            Date now = new Date();
            Date start = meeting.getTimStart();
            Date end = meeting.getTimEnd();
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            rMap.put("start", sdf.format(start));
            rMap.put("end", sdf.format(end));

            if(meeting.getNumStatus()==-1){
                rMap.put("txtStatus", "已取消");
            } else {
                if(now.getTime() > end.getTime()){  // 已召开
                    rMap.put("txtStatus", "已召开");
                } else if (now.getTime() > start.getTime()) {   // 召开中
                    rMap.put("txtStatus", "召开中");
                } else {    // 未召开
                    rMap.put("txtStatus", "未召开");
                }
            }
            if("Running".equals(meeting.getProcessState().name())){
                rMap.put("txtStatus", "流转中");
            }
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 列表 历史副本
     */
    @RequestMapping(value = "listHistory", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> listHistory(@CurrentUser User user,@RequestParam() String updateUnid) throws ParseException {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("createTime", SearchEnum.OrderType.asc);
        SearchResultPaging searchResult = null;

        List<Rule> rules = new ArrayList<Rule>();
        rules.add(RuleHelper.eq("company", company));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的
        rules.add(RuleHelper.eq("processState", FlowEnum.ProcessState.Destroy));  // 历史
        if (!updateUnid.isEmpty()) {
            rules.add(RuleHelper.eq("updateUnid", updateUnid));
        }

//        Map<String,Object> params = new HashMap<String,Object>();
//        params.put("company", company);
//        params.put("state", new BaseEnumManager.StateEnum[]{BaseEnumManager.StateEnum.Enable, BaseEnumManager.StateEnum.Delete});

        //所有单子
//        searchResult = meetingService.paging(null,rules,order,
//                "com.fz.us.oa.core.entity.com.Meeting",
//                new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished}, params);
        searchResult = meetingService.findPagingBySearch(null,rules,order);

        List<Meeting> meetingList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Meeting meeting: meetingList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", StringUtils.isEmpty(meeting.getId())?"":meeting.getId());
            rMap.put("name", StringUtils.isEmpty(meeting.getName())?"":meeting.getName());
            rMap.put("address", StringUtils.isEmpty(meeting.getAddress())?"":meeting.getAddress());
            rMap.put("chief", (meeting.getChief()==null)?"":meeting.getChief().getName());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            rMap.put("dateUpdate", (meeting.getDateUpdate()==null)?"":sdf.format(meeting.getDateUpdate()));
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 日程取消
     */
    @RequestMapping(value = "cancel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object cancel(@CurrentUser User user, String cancelReason, String keyId) {

        Meeting meeting = meetingService.get(keyId);
        meeting.setCancelReason(cancelReason);
        meeting.setNumStatus(-1);
        meeting.setTxtStatus("已取消");
        meeting.setProcessState(FlowEnum.ProcessState.Deny);

        //发送提醒
        Remind remind = new Remind();
        remind.setUser(meeting.getChief());
        remind.setBussinessKey("meeting");
        remind.setKeyId(keyId);
        remind.setContent("您有一次会议已被取消，请查看");
        remindService.save(remind);
        for(User user1:meeting.getParticipants()){
            Remind remind1 = new Remind();
            remind1.setUser(user1);
            remind1.setBussinessKey("meeting");
            remind1.setKeyId(keyId);
            remind1.setContent("您有一次会议已被取消，请查看");
            remindService.save(remind1);
        }

        return ajaxJson(meetingService.saveEntity(meeting));
    }

    /**
     * 保存会议纪要
     */
    @RequestMapping(value = "uploadfile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object saveFiles(@CurrentUser User user, String fileIds, String keyId) {

        Meeting meeting = meetingService.get(keyId);

        if (StringUtils.isNotBlank(fileIds)) {
            //hiddenFiles
            List<FileManage> fileManageList = Lists.newArrayList();
            if(StringUtils.isNotEmpty(fileIds)){
                for(String f:fileIds.split(",")){
                    fileManageList.add(fileManagerService.get(f.trim()));
                }
            }
            meeting.setFile(fileManageList);
        }

        return ajaxJson(meetingService.saveEntity(meeting));
    }

    /**
     * 完成修改操作
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public Object update(@CurrentUser User user,
                         @RequestParam(required = false) String keyId, String isOut,String isPublic,String name,
                         String datStart, String timStart, String datEnd, String timEnd, String subject,
                         String userId, String userIds,String outermen, String address,String aidSets, String otherSet,String curDutyId) throws ParseException {

        if (StringUtils.isNotBlank(keyId)) {
            Meeting meetingOld = meetingService.get(keyId);
            meetingOld.setNumStatus(-1);
            meetingOld.setTxtStatus("历史");
            meetingOld.setProcessState(FlowEnum.ProcessState.Destroy);
            meetingOld.setDateUpdate(new Date());
            if (meetingOld.getUpdateUnid() == null) {
                meetingOld.setUpdateUnid(keyId);
            }
            meetingService.saveEntity(meetingOld);
        }

        Meeting meeting = saveModel(user,"",isOut,isPublic,name,datStart,timStart,datEnd,timEnd,subject,userId,userIds,outermen,address,aidSets,otherSet);

        if(meeting == null){
            return ajaxJson(resultService.fail("保存业务数据失败！"));
        }

        meeting.setDateApply(new Date());
        meeting.setNumStatus(1);
        meeting.setTxtStatus("正常");
        meeting.setProcessState(FlowEnum.ProcessState.Finished);
        meeting.setUpdateUnid(meetingService.get(keyId).getUpdateUnid());
//        meetingService.commit(meeting, "com.fz.us.oa.core.entity.com.Meeting", dutyService.get(curDutyId));
//        meeting.setProcessState(FlowEnum.ProcessState.Finished);
        return ajaxJson(meetingService.saveEntity(meeting));
    }

    /**
     * 保存会议考勤
     */
    @RequestMapping(value = "updateSign",method = RequestMethod.POST)
    public Object updateSign(@CurrentUser User user,
                           @RequestBody List<MeetingSign> meetingSignList){
        for(MeetingSign sign:meetingSignList){
            if(sign.getSignType()!=0&&StringUtils.isNotEmpty(sign.getSignPlace())){
                MeetingSign meetingSign=meetingSignService.get(sign.getId());
                if(meetingSign!=null){
                    meetingSign.setSignType(sign.getSignType());
                    meetingSign.setSignPlace(sign.getSignPlace());
                    meetingSign.setIsSing(1);
                    meetingSignService.update(meetingSign);
                }
            }
        }

        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","操作成功");
        rMap.put("state","1");
        return ajaxJson(rMap);
    }


}
